package de.uni_mannheim.informatik.ai.dame_ai.util;

import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.regex.Pattern;


public class FileSystem {

	private static final String FS =System.getProperty("file.separator");
	
	public enum GameName{
		battleship,
		mill, 
		mensch_aergere,
		dame,
		main
	}
	
	public static File getGCDirectory(){
		String homeDir=System.getProperty("user.home");
		File millDir= new File(homeDir+FS+"h3m"+FS+"GameCollection");
		if(!millDir.exists()){
			boolean successful=millDir.mkdirs();
			if(successful){
				System.out.println("Created directories in user folder:");
				System.out.println("  "+millDir);
			}
		}
		return millDir;
	}
	
	public static File getDirectory(GameName game){
		File gameDirectory=new File(getGCDirectory(), game.toString());
		if(!gameDirectory.exists())
			gameDirectory.mkdirs();
		return gameDirectory;
	}
	
	public static File[] getSaveFiles(GameName game){
		File gameDir=getDirectory(game);
		File[] savedGames= gameDir.listFiles(new SaveGameFilter(game));
		Arrays.sort(savedGames, new LastModifiedCoparator());
		return savedGames;
	}
	
	public static File getQuickSave(GameName game){
		return new File(getDirectory(game),"quicksave");
	}
	
	public static File getAutoSave(GameName game){
		return new File(getDirectory(game),"autosave."+game+".xml");
	}
	
	public static File[] getLanguageFiles(GameName game){
		File langDirectory=new File(System.getProperty("user.dir")+FS+"lang"+FS+game.toString());
		File[] langFiles = langDirectory.listFiles();
		return langFiles;

//		File langDir=getDirectory(game);
//		File[] savedGames= gameDir.listFiles(new SaveGameFilter(game));
//		Arrays.sort(savedGames, new LastModifiedCoparator());
//		return savedGames;
//		return null;
	}
}


/**
 * Filters files according to the following naming convention:
 * The file name must end with .<GameName>.xml
 * @author Martin Boelle
 */
class SaveGameFilter implements FilenameFilter{
	Pattern validFileName;
	
	public SaveGameFilter(FileSystem.GameName game) {
		validFileName = Pattern.compile(".+\\."+game+"\\.xml");
	}

	@Override
	public boolean accept(File dir, String name) {
		return validFileName.matcher(name).matches();
	}
}

/**
 * Compares Dates in order to sort them <b>DESCENDING</b>
 * @author Martin Boelle
 */
class LastModifiedCoparator implements Comparator<File>{
	@Override
	public int compare(File o1, File o2) {
		return (int) (o2.lastModified()-o1.lastModified());
	}
}
